/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sqlcommand;

import data.Cell;
import data.ManagerDatabase;
import data.Row;
import data.Table;
import java.util.ArrayList;

/**
 *
 * @author Quang
 */
public class Insert extends Command {

    private String tableName;
    private ArrayList<String> cols;
    private ArrayList<String> values;

    public Insert(String strSQL, ManagerDatabase md) {
        super(strSQL, md);
        tableName = null;
        cols = new ArrayList<String>();
        values = new ArrayList<String>();
        sql = Command.standardizeString(strSQL);
    }

    @Override
    public Command getCommand(MyError err) {
        StringBuilder strBuff = new StringBuilder(this.getSql());
        int posInsert = strBuff.indexOf("INSERT");
        int posInto = strBuff.indexOf("INTO");
        int posValues = strBuff.indexOf("VALUES");
        if (posInsert == -1 || posInto == -1 || posValues == -1) {
            err.setError("Error! Khong chua tu khoa INSERT, INTO, VALUES");
            return null;
        }


        String tablesAndCols = strBuff.substring(posInto + 5, posValues);
        // kiem tra xem co du dau ngoac don khong
        int k = 0;
        for (int i = 0; i < strBuff.length(); i++) {
            if (strBuff.charAt(i) == '\'') {
                k++;
            }
            //kiem tra cac dau phay ',' co hop le khong?
            if (strBuff.charAt(i) == ',' && strBuff.charAt(i + 2) == ')') {
                err.setError("Error!! Du dau ','");
                return null;
            }
        }
        if (k % 2 != 0) {
            err.setError("Error!! thieu dau ngoac ''' ");
            return null;
        }
        //kiem tra xem co danh sach cac cot hay khong?
        int posNgoacMo = tablesAndCols.indexOf("(");
        if (posNgoacMo == -1) {
            if (checkAndSaveTableName(tablesAndCols, err)) {
                return null;
            }
        } else {// co danh sach cot
//            if (tablesAndCols.charAt(posNgoacMo + 1) != '\'') {
//                err.setError("Error! thieu dau '''");
//                return null;
//            }
            String table = tablesAndCols.substring(0, posNgoacMo);
            if (checkAndSaveTableName(table, err)) {
                return null;
            }

            int posNgoacDong = tablesAndCols.indexOf(")");
            if (posNgoacDong == -1) {
                err.setError("Error! Khong co ngoac dong");
                return null;
            }
//            if (tablesAndCols.charAt(posNgoacDong - 1) != '\'') {
//                err.setError("Error! thieu dau '''");
//                return null;
//            }
            // danh sach cac cot
            String colsName = tablesAndCols.substring(posNgoacMo , posNgoacDong+1);
            this.cols = TachChuoi(colsName, err);
            if (cols == null) {
                return null;
            }
        }
        String strValue = strBuff.substring(posValues + 6, strBuff.length());
        this.values = TachChuoi(strValue, err);
        if (values == null) {
            return null;
        }
        return this;
    }

    
    /**
     * tach chuoi dang ('abc',12,'def') thanh tung chuoi con abc, def
     *
     * @param str
     * @return danh sach chuoi
     */
    public ArrayList<String> TachChuoi(String str, MyError error) {
        // kiem tra dau nhay don va ngoac don
        StringBuilder colsName = new StringBuilder(str);
        ArrayList<String> arr = new ArrayList<>();
          if(colsName.charAt(0)!='('){
                error.setError("Error!! Thieu dau mo ngoac");
                return null;
            }
            else
                colsName.deleteCharAt(0);
            
            if(colsName.charAt(colsName.length()-1)!=')'){
                error.setError("Error!! Thieu dau dong ngoac");
                return null;
            }
            else
                colsName.deleteCharAt(colsName.length()-1);
        while (true) {
          
            
            int posComma = colsName.indexOf(",");
            if (posComma != -1) {
                String col;
                if (colsName.charAt(0) == '\'') {
                    col = colsName.substring(1, posComma - 1);
                } else {
                    col = colsName.substring(0, posComma);
                }
                if (col.indexOf(" ") != -1) {
                    error.setError("Error! Ten  cot khong hop le");
                    return null;
                } else {
                    arr.add(col);
                    colsName.delete(0, posComma + 2);
                }
            } else {
                if (colsName.indexOf(" ") != -1) {
                    error.setError("Error! Ten cot khong hop le");
                    return null;
                } else {
                    if (colsName.charAt(0) == '\'') {
                        colsName.deleteCharAt(0);
                    }
                    if (colsName.charAt(colsName.length() - 1) == '\'') {
                        colsName.deleteCharAt(colsName.length() - 1);
                    }
                    arr.add(colsName.toString());
                    break;
                }
            }
        }
        return arr;
    }
/**
 * insert 1 dong vao trong co so du lieu
 * @return dong duoc insert vao CSDL
 * tra ve null neu ko insert dc
 */
    @Override
    public ArrayList<Row> excute(MyError err) {
        Table table = manager.getTable(tableName);
        int nCell = table.getListCol().size();
        ArrayList<Cell> cells = new ArrayList<>();
        
       
        for(int i=0; i<table.getnCols(); i++){
            Cell cell = new Cell();
            cell.setName(table.getListCol().get(i).getName());
            cells.add(cell);
        }
        for(int i=0; i<this.cols.size(); i++){
            if(cells.get(i).getName().equals(cols.get(i))){
                cells.get(i).setData(values.get(i));
            }
            else
                cells.get(i).setData("");
        }
     
        
       ArrayList<Row> row = new ArrayList<>();
       row.add(new Row(cells, nCell, 0));
       table.insertRow(row.get(0));
        return row;
    }

    public boolean checkAndSaveTableName(String tablesAndCols, MyError err) {
        // ko co danh sach cot
        tablesAndCols = Command.ChuanHoa(tablesAndCols);
        if (tablesAndCols.indexOf(" ") != -1) {
            err.setError("Error! Ten bang khong duoc chua dau khoang trang");
            return true;
        } else {
            tableName = tablesAndCols;
        }
        
        Table t =  manager.getTable(tableName);
        for(int i=0; i<t.getListCol().size(); i++){
            this.cols.add(t.getListCol().get(i).getName());
        }
        return false;
    }

    /**
     * @return the tableName
     */
    public String getTableName() {
        return tableName;
    }

    /**
     * @return the cols
     */
    public ArrayList<String> getCols() {
        return cols;
    }

    /**
     * @return the values
     */
    public ArrayList<String> getValues() {
        return values;
    }
}
